package arithmetic3.bitmap;

/**
 * @author 姚凤桥
 * @Date 2021/12/15 10:44
 * @Description: 布隆过滤器
 */
public class BlondFilter {
    private int size;

    private BitMap bitMap;

    /**
     * 指定布隆过滤器的容量
     *
     * @param size
     */
    public BlondFilter(int size) {
        this.size = size;
        this.bitMap = new BitMap(new int[size >> 5]);
    }

    /**
     * 向过滤器中添加一个url
     *
     * @param url
     */
    public void addUrl(String url) {
        int index = Math.abs(url.hashCode()) % size;
        bitMap.modifyIndexOne(index);
    }

    /**
     * 判断url是否存在
     *
     * @param url
     * @return
     */
    public boolean isExist(String url) {
        int index = Math.abs(url.hashCode()) % size;
        return bitMap.getIndexStatus(index) == 1;
    }

    public static void main(String[] args) {
        String url1 = "www.baidu.com";
        String url2 = "www.tengxun.com";
        String url3 = "www.alibaba.com";
        String url4 = "www.wangyi.com";
        String url5 = "www.huawei.com";

        //创建一个整型数组长度为100的过滤器(bitMap大小为3200)
        BlondFilter blondFilter = new BlondFilter(3200);

        //添加5个黑名单
        blondFilter.addUrl(url1);
        blondFilter.addUrl(url2);
        blondFilter.addUrl(url4);
        blondFilter.addUrl(url3);
        blondFilter.addUrl(url5);

        System.out.println(blondFilter.isExist("www.huawei.com"));
    }
}
